<script lang="js" setup>
import {onBeforeRouteLeave, useRoute} from "vue-router"
import {createDiscreteApi, NButton, NCard, NDivider, NGrid, NGridItem, NTag} from "naive-ui"
import PaperTestItem from "~/components/PaperTestItem.vue";


// 实例话
const route = useRoute()


// 开始考试
let {data} = await useReadTestpaperApi(route.params.id)


// 计算列表
const testpaper_questions = computed(() => {
  return data.value ? data.value.testpaper_questions.map((o) => {
    o.isText = false
    return o
  }) : []
})

const handleUserValueChange = (item, val) => {
  item.user_value = val;
  updateIsTest()
}

const updateIsTest = () => {
  testpaper_questions.value.forEach((item) => {
    let t = false
    // 问答和填空
    if (item.type === "answer" || item.type === "completion") {
      t = !!item.user_value[0]
    }

    // 单选
    else if (item.type === "radio" || item.type === "trueOrfalse") {
      t = item.user_value !== -1
    }

    // 多选
    else {
      t = item.user_value.length > 0
    }
    item.isText = t
  })
}

// 滚动到指定位置
const scrollToDom = (index) => {
  const dom = document.getElementById('question_' + index)
  window.scrollTo(0, dom.offsetTop)
}


const disableBack = ref(true)
onBeforeRouteLeave((to, form, next) => {
  if (!disableBack.value) {
    next()
  } else {
    const {dialog} = createDiscreteApi(['dialog']);
    dialog.warning({
      content: "是否要放弃考试?",
      positiveText: "确定",
      negativeText: "取消",
      onPositiveClick: () => {
        disableBack.value = false;
        navigateTo(to.fullPath || "/", {replace: true})
      }
    })
    next(false)
  }
})

// 交卷
const loading = ref(false)
const submit = async () => {
  const {message} = createDiscreteApi(['message']);
  const i = testpaper_questions.value.filter((o) => !o.isText).length;

  if (i > 0) {
    return message.warning("还有题目没有完成，请检查")
  }

  loading.value = true;

  const {error: submitError, data: submitData} = await useSubmitTestApi({
    user_test_id: data.value.user_test_id,
    value: testpaper_questions.value.map((o) => o.user_value)
  })
  loading.value = false
  if (submitError.value) return
  // 跳转之前disableBack设置true
  disableBack.value = false;
  message.success("交卷成功");
  navigateTo("/paper/1", {replace: true})
}


// 自定交卷
const autoSubmit = () => {
  const {dialog} = createDiscreteApi(['dialog']);
  dialog.success({
    content: "考试时间到，试卷已强制提交?",
    positiveText: "确定",
    closable: false,
    onPositiveClick: () => {
      disableBack.value = false;
      navigateTo("/paper/1", {replace: true})
    }
  })
}

definePageMeta({
  middleware: ['auth']
})

</script>

<template>
  <n-grid :x-gap="20">
    <n-grid-item :span="18">
      <n-card>
        <template #header>
          <h3 class="text-center font-bold">{{ data.title }}</h3>
          <n-divider/>
          <p class="space-x-5 text-sm text-center">
            <span>科目总数：{{ data.testpaper_questions.length }}</span>
            <span>总分数：{{ data.total_score }}</span>
            <span>时间：{{ data.expire }}分钟</span>
          </p>
        </template>

        <!-- 题目组件 -->
        <PaperTestItem v-for="(item,index) in testpaper_questions" :id="'question_' + index" :key="index"
                       :index="index" :item="item" @change="handleUserValueChange(item,$event)"/>
      </n-card>
    </n-grid-item>

    <n-grid-item :span="6">
      <n-card>
        <template #header>
          <div class="flex flex-col items-center justify-center">
            <small class="text-gray-500 mb-1">剩余时间</small>
            <TimeBox :expire="data.expire" class="text-light-blue-600 text-3xl" @end="autoSubmit"/>
          </div>
        </template>

        <n-grid :cols="4" :x-gap="20">
          <n-grid-item v-for="(item,index) in testpaper_questions" :key="index" @click="scrollToDom(index)">
            <n-tag :type="item.isText ? 'success' :'default'"
                   class="mb-2 cursor-pointer w-full flex justify-center items-center">{{ index + 1 }}
            </n-tag>
          </n-grid-item>
        </n-grid>
        <n-divider/>
        <div>
          <n-button :loading="loading" class="w-full" type="primary" @click="submit">交 卷</n-button>
        </div>
      </n-card>
    </n-grid-item>
  </n-grid>
</template>

<style scoped>

</style>
